using System;
using System.IO;
using System.Collections;
using System.Diagnostics;
using System.Reflection;

namespace Copperline.Escriba
{
	/// <summary>
	/// Sinks log events to the <c>System.Diagnostics.Debug</c> facility.
	/// </summary>
	public class DebugLogger : LoggerBase
	{
		/// <summary>
		/// Creates an instance of the class <c>DebugLogger</c>.
		/// </summary>
		/// <remarks>The default configuration suppresses the fields <c>EField.datetime</c>
		/// and <c>EField.Ident</c>.</remarks>
		public DebugLogger()
		{
			Init( ESeverity.debug, ETrigger.threshold );
		}

		/// <summary>
		/// Creates an instance of the class <c>DebugLogger</c>.
		/// </summary>
		/// <param name="severity">The minimum severity required before a logging event will
		/// be logged</param>
		/// <param name="trigger">Whether the threshold or matching trigger will be used when
		/// comparing severities.</param>
		public DebugLogger( ESeverity severity, ETrigger trigger )
		{
			Init( severity, trigger );
		}

		/// <summary>
		/// Writes a log entry to the debug process
		/// </summary>
		/// <param name="logEntry">the log entry to write</param>
		public override void Write( LogEntry logEntry )
		{
			StringWriter sw = new StringWriter();
			Append( sw, logEntry );
			sw.Close();
			if( sw.GetStringBuilder().Length > 0 )
				Debug.WriteLine( sw.GetStringBuilder().ToString().Trim() );
		}

		private void Init( ESeverity severity, ETrigger trigger )
		{
			Enabled = true;
			TextFormatter formatter = new TextFormatter();
			formatter.SetFieldSequence(
				new FieldFormatter( Type.GetType("Copperline.Escriba.LogEntry").GetProperty("SeverityName"), LogEntry.SeverityFormat ) );

			formatter.FieldSeparator = " ";
			this.Formatter = formatter;

			SeverityFilter filter = new SeverityFilter( severity, trigger );
			this.Filter = filter;
		}
	}
}
